import { defineStore } from 'pinia'
import { shallowRef, ref } from 'vue'
import { getWebsiteInfo } from '@/apis/website'
import type { WebsiteInfo } from '@/apis/website'
import { returnTime } from '@/utils/tool'

const useWebsiteStore = defineStore('website', () => {
  const webInfo = shallowRef<WebsiteInfo | null>(null)
  const lastFetchedTime = shallowRef<number | null>(null)
  const loading = ref(false)
  const CACHE_EXPIRATION_TIME = 1000 * 60 * 60

  const getInfo = async () => {
    const currentTime = new Date().getTime()

    // 若缓存有效，直接返回
    if (
      webInfo.value &&
      lastFetchedTime.value &&
      currentTime - lastFetchedTime.value < CACHE_EXPIRATION_TIME
    ) {
      return webInfo.value
    }

    loading.value = true
    try {
      const res = await getWebsiteInfo()
      res.lastUpdateTime = returnTime(res.lastUpdateTime) as string
      setInfo(res)
    } catch (error) {
      console.error('获取网站信息失败', error)
    } finally {
      loading.value = false
    }

    return webInfo.value
  }

  const setInfo = (data: WebsiteInfo) => {
    webInfo.value = data
    lastFetchedTime.value = new Date().getTime()
  }

  return {
    webInfo,
    loading,
    getInfo,
    setInfo
  }
})

export default useWebsiteStore
